package net.myspring.common.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import net.myspring.common.utils.Const;
import net.myspring.common.utils.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created by liuj on 2016-09-10.
 */
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
        LocalDateTime localDateTime = null;
        if(StringUtils.isNotBlank(p.getText())) {
            String pattern = "yyyy-MM-dd HH:mm:ss";
            if(p.getText().length() != pattern.length()) {
                pattern = "yyyy-MM-dd HH:mm";
            }
            DateTimeFormatter formatter =  DateTimeFormatter.ofPattern(pattern);
            localDateTime = LocalDateTime.parse(p.getText(),formatter);
        }
        return localDateTime;
    }
}
